//
//  WCNMeCommentsVC.m
//  WCN
//
//  Created by 杨鑫 on 15/6/2.
//  Copyright (c) 2015年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNMeCommentsVC.h"
#import "WCNCommentVC.h"
//
#import "MJRefresh.h"
#import "WCNCommentTCell.h"
#import "NoRecordsView.h"
//
#import "UILabel+Utilities.h"
#import "NSString+Utilities.h"
//
#import "WCDefaultManager.h"
#import "WCCoreDataStore.h"
#import "WCNetworkAccessManager.h"
//
#import "Macros.h"
#import "Constants.h"

static NSString *cellId = @"WCNCommentTCell";
static int pageSize = 10;

@interface WCNMeCommentsVC ()

@property (strong, nonatomic) NSMutableArray *comments;
@property (strong, nonatomic) NSString *url;
@property (nonatomic) int pageNum;

@property (strong, nonatomic) WCNCommentTCell *propotyCell;

@end

@implementation WCNMeCommentsVC

- (instancetype)init
{
    self = [super initWithStyle:UITableViewStylePlain];
    if (self) {
        self.title = @"全部评价";
        
        _comments = [NSMutableArray array];
        [_comments addObjectsFromArray:[[WCCoreDataStore shareStore] getComments]];
        
        _url = @"nursing/order/comment/list";
        _pageNum = 0;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = kAppBg;
    
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.tableView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellReuseIdentifier:cellId];
    
    __weak typeof(self) weakSelf = self;
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        [weakSelf refreshComments];
    }];
    
    self.propotyCell = [self.tableView dequeueReusableCellWithIdentifier:cellId];
    self.propotyCell.content.numberOfLines = 0;
    //加上跨度约束后，动态计算高度才有效
    [self.propotyCell.contentView addConstraint:[NSLayoutConstraint constraintWithItem:self.propotyCell.contentView
                                                                             attribute:NSLayoutAttributeWidth
                                                                             relatedBy:NSLayoutRelationEqual
                                                                                toItem:nil
                                                                             attribute:NSLayoutAttributeNotAnAttribute
                                                                            multiplier:1
                                                                              constant:kScreenWidth]];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if ([[WCNetworkAccessManager sharedMg] timeSinceLastUrl:self.url] > kUrlCD && ![self.tableView.header isRefreshing]) {
        [self.tableView.header beginRefreshing];
    } else {
        if (self.comments.count == 0) {
            self.tableView.tableHeaderView = [[NoRecordsView alloc] init];
        }
    }
}

- (void)refreshComments
{
    Account *account = [[WCDefaultManager shareMg] account];
    NSDictionary *params = @{@"nurseId":account.stringId, @"pageNum":@1, @"pageSize":@(pageSize)};
    [[WCNetworkAccessManager sharedMg] POST:self.url parameters:params success:^(NSDictionary *result){
        NSDictionary *page = result[@"data"];
        self.pageNum = [page[@"currentPage"] intValue];
        if ([page[@"totalPage"] intValue] > 1) {
            [self addFooterRefreshMode];
        }
        self.comments = [NSMutableArray arrayWithArray:[[WCCoreDataStore shareStore] createComments:page[@"pageData"] save:YES]];
        if (self.comments.count == 0) {
            self.tableView.tableHeaderView = [[NoRecordsView alloc] init];
        } else {
            self.tableView.tableHeaderView = nil;
        }
        [self.tableView reloadData];
    } failure:nil netError:nil always:^{
        [self.tableView.header endRefreshing];
    }];
}

- (void)addFooterRefreshMode
{
    __weak typeof(self) weakSelf = self;
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        [weakSelf moreData];
    }];
    self.tableView.footer.automaticallyRefresh = NO;
}

- (void)moreData
{
    Account *account = [[WCDefaultManager shareMg] account];
    NSDictionary *params = @{@"nurseId":account.stringId, @"pageNum":@(self.pageNum+1), @"pageSize":@(pageSize)};
    [[WCNetworkAccessManager sharedMg] POST:self.url parameters:params success:^(NSDictionary *result){
        NSDictionary *page = result[@"data"];
        self.pageNum = [page[@"currentPage"] intValue];
        if ([page[@"totalPage"] intValue] == self.pageNum) {
            [self.tableView removeFooter];
            [self.tableView.footer removeFromSuperview];
        }
        [self.comments addObjectsFromArray:[[WCCoreDataStore shareStore] createComments:page[@"pageData"] save:NO]];
        [self.tableView reloadData];
    } failure:nil netError:nil always:^{
        [self.tableView.footer endRefreshing];
    }];
}

#pragma mark - <UITableViewDelegate, UITableViewDataSource>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.comments.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WCNCommentTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    Comment *comment = self.comments[indexPath.row];
    cell.name.text = comment.mobile;
    cell.avgFen.text = [NSString stringWithFormat:@"%.1f", comment.ratingGeneral];
    
    comment.content = [comment.content trim];
    if ([comment.content isEmpty]) {
        cell.content.text = @"该用户很懒，没有留下文字评论";
    } else {
        cell.content.text = comment.content;
    }
    [cell.content showAttributedText:0 lineSpace:6];
    
    cell.time.text = comment.commentTime;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    Comment *comment = self.comments[indexPath.row];
    self.propotyCell.content.text = comment.content;
    [self.propotyCell.content showAttributedText:0 lineSpace:5];
    
    CGSize size = [self.propotyCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
    return MAX(kOnePX+size.height, 104.0);
}

@end
